package appclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import http_tunnel.*;

public class HandleClient
{
	private String server_host;
	private int port;
	private Client client;

	private Socket socket;
	private Output out;
	private Input in;
	private boolean connectionClosed;

	public HandleClient(String server_host, int port, Client client)
	{
		this.server_host = server_host;
		this.port = port;
		this.client = client;
	}
	
	/**
	 * Ouverture de la connexion au serveur.
	 */
	protected void openConnection()
	{
		try 
		{
			socket = new Socket(server_host, port);
			out = new Output(socket);
			in = new Input(socket);
			connectionClosed = false;
			System.out.println("[OK] La connection au serveur " + server_host + " sur le port " + port + " s'est deroulee avec succes.");
		} 
		catch (IOException e) 
		{
			System.out.println("[ERROR] Impossible de se connecter au serveur " + server_host + " sur le port " + port + ".");
			e.printStackTrace();
		}
	}

	/**
	 * Fermeture de la connexion au serveur.
	 */
	protected void closeConnection()
	{
		try 
		{
			socket.close();
			out.close();
			in.close();
			connectionClosed = true;
			System.out.println("La fermeture de la connection au serveur " + server_host + " sur le port " + port + " s'est d�roul�e avec succ�s.");
		} 
		catch (IOException e)
		{
			System.out.println("[ERROR] Impossible de fermer la connexion au serveur " + server_host + " sur le port " + port + ".");
			e.printStackTrace();
		}
	}
	
	protected void sendToServer(String httpPaket)
	{
		out.print(httpPaket);
	}
	
	protected String receiveFromServer()
	{
		try {
			return in.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
}
